package world3d;

import java.awt.AWTEvent;
import java.awt.event.KeyEvent;
import java.util.Enumeration;

import javax.media.j3d.Transform3D;
import javax.media.j3d.WakeupCondition;
import javax.media.j3d.WakeupCriterion;
import javax.media.j3d.WakeupOnAWTEvent;
import javax.vecmath.Vector3d;

import com.sun.j3d.utils.behaviors.vp.*;

/**
 * Keyboard event handlers
 * 
 * @author bastian marquis
 */
public class KeyboardEvent extends ViewPlatformBehavior {
	
	private IWorld w;
	private WakeupCondition keyPressed;
	
	public KeyboardEvent(IWorld w){
		this.w = w;
		keyPressed = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED);
	}

	@Override
	public void initialize() {
		wakeupOn(keyPressed);
	}

	@Override
	public void processStimulus(Enumeration arg0) {
		WakeupCriterion wakeup;
		AWTEvent[] event;
		
		while(arg0.hasMoreElements()){
			wakeup = (WakeupCriterion)(arg0.nextElement());
			if(wakeup instanceof WakeupOnAWTEvent){
				event = ((WakeupOnAWTEvent)wakeup).getAWTEvent();
				
				for(AWTEvent e : event){
					if(e.getID() == KeyEvent.KEY_PRESSED)
						processKeyPressedEvent((KeyEvent)e);
				}
			}
		}
		
		wakeupOn(keyPressed);
	}
	
	private void processKeyPressedEvent(KeyEvent k){
		Transform3D t3d = new Transform3D();
		Transform3D toMove = new Transform3D();
		Vector3d theMove = null;
		targetTG.getTransform(t3d);
		
		switch(k.getKeyCode()){
		
		case KeyEvent.VK_UP :
			theMove = new Vector3d(0, 0, 1);
			toMove.setTranslation(theMove);
			break;
			
		case KeyEvent.VK_DOWN :
			theMove = new Vector3d(0, 0, -1);
			toMove.setTranslation(theMove);
			break;
			
		case KeyEvent.VK_LEFT :
			toMove.rotY(Math.PI / 4);
			break;
			
		default :	
			return;
		}
		
		t3d.mul(toMove);
		targetTG.setTransform(t3d);
	}
}
